package data.email;

import data.TokenCounter;
import data.Document;
import data.DocumentCollection;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Koleksi dokumen email
 * @author Robert Gunawan
 */
public class EmailDocumentCollection implements DocumentCollection {

    /**
     * jumlah dokumen
     */
    public Integer documentCount;
    /**
     * koleksi dokumen dalam bentuk antrian
     */
    private Queue<Document> documentCollection;
    /**
     * lock untuk akses koleksi
     */
    final private Object documentCollection_lock = new Object();
    /**
     * penanda apakah crawling sudah selesai
     */
    private boolean finishedCollecting;
    /**
     * lock untuk penanda proses crawling
     */
    final private Object finishedCollecting_lock = new Object();
    /**
     * token counter
     */
    private EmailTokenCounter tokenCounter;

    /**
     * konstruktor dari EmailDocumentCollection
     */
    public EmailDocumentCollection() {
        documentCollection = new LinkedList<Document>();
        finishedCollecting = false;
        documentCount = 0;
        tokenCounter = new EmailTokenCounter();
    }

    @Override
    public void addDocument(Document document) {
        synchronized (documentCollection_lock) {
            documentCount++;
            documentCollection.add(document);
        }
    }

    @Override
    public Document getDocument() {
        synchronized (documentCollection_lock) {
            return documentCollection.poll();
        }
    }

    @Override
    public boolean isFinishedCollecting() {
        synchronized (finishedCollecting_lock) {
            return finishedCollecting;
        }
    }

    @Override
    public void setIsFinishedCollecting(boolean value) {
        synchronized (finishedCollecting_lock) {
            finishedCollecting = value;
        }
    }

    @Override
    public void addDocuments(ArrayList<Document> documents) {
        synchronized (documentCollection_lock) {
            documentCount += documents.size();
            documentCollection.addAll(documents);
        }
    }

    @Override
    public Integer getDocumentCount() {
        synchronized (documentCollection_lock) {
            return new Integer(documentCollection.size());
        }
    }

    @Override
    public void setTokenCouter(TokenCounter counter) {
        this.tokenCounter = (EmailTokenCounter) counter;
    }

    @Override
    public TokenCounter getTokenCounter() {
        return this.tokenCounter;
    }
}
